<template>
  <div class="dingjin">
    <div class="yingfu">
      <span>应付金额：</span><span>￥{{ this.price }}元</span>
    </div>
    <van-radio-group v-model="radio">
      <ul class="fuzhang">
        <li>
          <img src="../../../assets/dingdanxinxi/kehuyue.jpg" alt=""/>
          <span>{{ fukuan[0].text }}</span>
          <van-radio class="radio_checke_fukuan_style" value="账户余额" name="账户余额"></van-radio>
        </li>
        <li>
          <img src="../../../assets/dingdanxinxi/zhifubao.jpg" alt=""/>
          <span>{{ fukuan[1].text }}</span>
          <van-radio class="radio_checke_fukuan_style" value="支付宝" name="支付宝"></van-radio>
        </li>
        <li>
          <img src="../../../assets/dingdanxinxi/weixin.jpg" alt=""/>
          <span>{{ fukuan[2].text }}</span>
          <van-radio class="radio_checke_fukuan_style" value="微信" name="微信"></van-radio>
        </li>
      </ul>
    </van-radio-group>
    <div class="tongyi_yuedu">
      <van-checkbox class="ckecked_tongyi_ground_btn" v-model="checked" shape="square"/>
      <span>同意</span>
      <span>《平价分时租车租赁协议》</span>
    </div>
    <div class="dingjin">
      <!-- 优惠券单元格 -->
      <van-coupon-cell
          :coupons="unableCoupons"
          :chosen-coupon="chosenCoupon"
          @click="getUserCoupon()"
      />
      <!-- 优惠券列表 -->
      <van-popup
          v-model="showList"
          round
          position="bottom"
          style="height: 90%; padding-top: 4px;"
      >
        <van-coupon-list
            :coupons="unableCoupons"
            :chosen-coupon="chosenCoupon"
            :disabled-coupons="disabledCoupons"
            @change="onChange"
            @exchange="onExchange"
        />
      </van-popup>
    </div>
    <van-button :disabled="!checked" class="buton_botom" type="info" @click="fukuantotongzhi">
      {{ radio }}
    </van-button>
    <div>
      <van-popup :style="{ width: '80%', height: '45%', padding: '10px' }" v-model="show3">
        <div class="sg-qrcode">
          <vue-qr :text="code_url" :correctLevel="3" :size="250" :margin="10" colorDark="blue" colorLight="white"
                  backgroundColor="white" backgroundDimming="white" :logoScale="0.2" :logoMargin="5"
                  logoBackgroundColor="black"></vue-qr>
          <h2>请用支付宝扫码支付</h2>
          <div>订单的状态:{{ paystatus }}</div>
          <van-button class="log" round block type="info" :style="{ width: '150px', height: '50px', margin: '0 auto' }"
                      @click="yizhifu">
            已支付
          </van-button>
        </div>
      </van-popup>
    </div>
    <div>
      <van-popup :style="{ width: '80%', height: '45%', padding: '10px' }" v-model="show2">
        <div class="sg-qrcode">
          <vue-qr :text="code_url" :correctLevel="3" :size="250" :margin="10" colorDark="green" colorLight="white"
                  backgroundColor="white" backgroundDimming="white" :logoScale="0.2" :logoMargin="5"
                  logoBackgroundColor="black"></vue-qr>
          <h2>请用微信扫码支付</h2>
          <div>订单的状态:{{ paystatus }}</div>
          <van-button class="log" round block type="info" :style="{ width: '150px', height: '50px', margin: '0 auto' }"
                      @click="yizhifu">
            已支付
          </van-button>
        </div>
      </van-popup>
    </div>
    <div>
      <van-popup position="bottom" :style="{ width: '100%', height: '45%', padding: '10px' }" v-model="show1">
        <div>
          <span>已有金额: </span><span>￥{{ this.$store.state.user.accountBalance }}元</span>
          <p></p>
          <span>
            <span v-if="this.z_money!=this.price" style="text-decoration:line-through;color: red">应付:￥{{ this.z_money }}</span>
            <span style="color: #2ba245">应付:￥{{ this.price }}</span>
          </span>
          <br><br>
          <van-button class="log" round block type="info" :style="{ width: '150px', height: '50px', margin: '0 auto' }"
                      @click="jinezhifu">
            支付
          </van-button>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import {getNativeCodeUrl2, queryPayStatus2, useAmount, useCoupon} from "../../../request/userinfo/userinfo";
import {Notify} from "vant";
import vueQr from 'vue-qr';

Vue.use(vueQr);
export default {
  props: {},
  data() {
    return {
      show1: false,
      show2: false,
      show3: false,
      showList: false,
      radio: "账户余额",
      checked: false,
      fukuan: [{text: "账户余额"}, {text: "支付宝"}, {text: "微信"}],
      z_money: 0,
      paystatus: "",
      code_url: "",
      preparidAmount: "",
      id: "",
      carId: "",
      startTime: "",
      memberId: "",
      endTime: "",
      brrowShop: "",
      returnShop: "",
      chosenCoupon: -1,
      price: "",
      unableCoupons: [],
      disableCoupons: [],
      disabledCoupons: [],
      coupons: [],
      orderMsg: {},
      // 支付宝充值的uuid
      apiPayOrderUuid: "",
      // 微信充值的uuid
      weChatOrderUuid: "",
      isUseCoupon:-1
    };
  },
  created() {
    this.getUserCoupon()
  },
  methods: {
    onExchange(code) {
      console.log(code)
    },
    getUserCoupon() {
      this.$http.get("/customer/api/tbUserCoupon/selectUserCon/" + localStorage.getItem("ms_username")).then(resp => {
        this.showList = true
        if (resp.data.code === 2000) {
          this.unableCoupons = []
          this.disabledCoupons = []
          resp.data.data.forEach(e => {
            console.log(e)
            if (e.tbCoupon.amount > this.z_money) {
              this.disabledCoupons.push(
                  {
                    id: e.couponId,
                    name: e.couponName,
                    startAt: e.stime,
                    endAt: e.etime,
                    value: (e.tbCoupon.amount * 100),
                    description: e.tbCoupon.note,
                    valueDesc: (e.tbCoupon.amount) + '',
                    unitDesc: '元',
                    condition: '无使用门槛',
                  }
              )
            } else {
              this.unableCoupons.push(
                  {
                    id: e.couponId,
                    name: e.couponName,
                    startAt: e.stime,
                    endAt: e.etime,
                    value: (e.tbCoupon.amount * 100),
                    description: e.tbCoupon.note,
                    valueDesc: (e.tbCoupon.amount) + '',
                    unitDesc: '元',
                    condition: '无使用门槛',
                  }
              )
            }
          })
        }
      })
    },
    jinezhifu() {
      if (this.radio != "微信" && this.radio != "支付宝") {
        if (this.$store.state.user.accountBalance < this.price) {
          Notify({type: "danger", message: "余额不足请充值"});
        }
      }
      if (this.coupons == '') {
        this.chosenCoupon = -1
      } else {
        this.orderMsg.couponId = this.unableCoupons[this.chosenCoupon].id
      }
      useAmount(this.orderMsg)
          .then((res) => {
            if (res.code === 2000) {
              this.$store.state.order.orderno = res.data.orderNo;
              this.$store.state.order.startTime = res.data.startTime
              this.$store.state.order.endTime = res.data.endTime
              this.$router.push("/dingdantongzhi");
              this.show1 = false;
            } else if (res.code == 5000) {
              Notify({type: "danger", message: "余额不足请充值"});
            }
          });
    },
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index;
      this.coupons = []
      this.coupons.push(this.unableCoupons[index])
      this.isUseCoupon=this.unableCoupons[index].id
      this.price = this.z_money;
      this.price = this.price - this.unableCoupons[index].valueDesc / 1;
      if (this.price < 0) {
        this.price = 0
      }
      // chosenCoupon.value = index;
    },
    youhuojuan() {
      this.showList = true;
      this.price = this.z_money;
      useCoupon({
        shopId: this.$store.state.brrowShop,
        memberId: this.$store.state.user.id
      })
          .then((res) => {
            var newData = [];
            for (var i = 0; i < res.data.length; i++) {
              // val.push(res.data.data[i].amount);
              // nam.push(res.data.data[i].name);
              var obj = {
                name: res.data[i].name,
                value: res.data[i].amount * 100,
                id: res.data[i].id,
                valueDesc: res.data[i].amount,
                unitDesc: '元',
                condition: res.data[i].name,
                startAt: parseInt(new Date(res.data[i].startTime).getTime() / 1000),
                endAt: parseInt(new Date(res.data[i].endTime).getTime() / 1000),
              };
              newData.push(obj);
              console.log(newData)
            }
            this.coupons = newData;
            if (newData == null) {
              this.components = this.coupon;
            }
          });
    },
    yizhifu() {
      if (this.radio == "微信") {
        console.log("微信支付校验")
        if (this.weChatOrderUuid != "") {
          this.$http.get("rent/order/checkOrderStatus/" + this.weChatOrderUuid).then(resp => {
            if (resp.data.code === 2000) {
              Notify({type: 'success', message: '支付成功'});
              this.show2 = false
              this.$router.push("/dingdantongzhi");
            } else {
              Notify({type: 'warning', message: '订单可能还未支付'})
            }
          })
        }
      } else if (this.radio == "支付宝") {
        console.log("支付宝")
        console.log(this.apiPayOrderUuid)
        // 安全判断
        if (this.apiPayOrderUuid != "") {
          this.$http.get("rent/order/checkOrderStatu/" + this.apiPayOrderUuid).then(resp => {
            if (resp.data.code == 2000) {
              Notify({type: 'success', message: '支付成功！'});
              this.show3 = false
              this.$router.push("/dingdantongzhi");
            } else {
              Notify({type: 'warning', message: '订单可能还未支付'});
            }
          })
        }
      }
      // queryPayStatus2({
      //   orderNo: this.$store.state.carinfo.orderNo,
      //   carId: this.$store.state.carinfo.id,
      // })
      //     .then((r) => {
      //       this.paystatus = r.data.trade_state_desc;
      //       if (r.code == 2000) {
      //         // addorder({
      //         //   orderno: this.id,
      //         //   preparidAmount: this.preparidAmount,
      //         //   totalPrice: this.z_money,
      //         //   memberId: this.$store.state.user.id,
      //         //   carId: this.$store.state.carinfo.id,
      //         //   startTime: this.$store.state.startime,
      //         //   endTime: this.$store.state.endtime,
      //         //   brrowShop: this.$store.state.brrowShop,
      //         //   returnShop: this.$store.state.brrowShop,
      //         //   payStyle: this.$store.state.payStyle[1].code
      //         // })
      //         //     .then((res) => {
      //         //       this.$store.state.order = res.data;
      //         // /dingdantongzhi 原来跳转路径
      //         this.$router.push("/banner");
      //         this.dialogVisible = false;
      //         //     });
      //       } else {
      //         alert("未检测到支付完成，请重新点击按钮");
      //       }
      //     });
    },
    fukuantotongzhi() {
      // 准备订单需要的数据
      this.orderMsg = {
        couponId: this.isUseCoupon,
        price: this.price,
        userId: this.$store.state.user.id,
        carId: this.$store.state.carinfo.id,
        startTime: this.$store.state.startime,
        endTime: this.$store.state.endtime,
        brrowShop: this.$store.state.brrowShop,
        returnShop: this.$store.state.brrowShop,
        payStyle: this.$store.state.payStyle[0].code,
        orderNo: this.$store.state.carinfo.orderNo,
        username: this.$store.state.user.username,
        brrowLocale: this.$store.state.address.provide + "/" + this.$store.state.address.area + "/" + this.$store.state.address.city,
        rentLocale: this.$store.state.address.provide + "/" + this.$store.state.address.area + "/" + this.$store.state.address.city,
      }
      this.$store.state.order=this.orderMsg
      console.log(this.radio)
      // "2020-11-26 08:18:55 "
      let stime = this.$store.state.startime_;
      let etime = this.$store.state.endtime_;
      let new_stime =
          stime.getFullYear() +
          "-" +
          (stime.getMonth() + 1) +
          "-" +
          stime.getDate() +
          " " +
          new Date().getHours() +
          ":" +
          new Date().getMinutes() +
          ":" +
          new Date().getSeconds();
      let new_etime =
          etime.getFullYear() +
          "-" +
          (etime.getMonth() + 1) +
          "-" +
          etime.getDate() +
          " " +
          new Date().getHours() +
          ":" +
          new Date().getMinutes() +
          ":" +
          new Date().getSeconds();
      console.log(new_stime);
      console.log(this.z_money, this.$store.state.user.accountBalance);
      if (this.radio == "微信") {
        console.log("生产微信支付订单")
        this.show2 = true;
        this.orderMsg.state = 0
        this.$http.post("/rent/order/productionWxPay", this.orderMsg).then(resp => {
          console.log(resp)
          this.code_url = resp.data.data.codeUrl
          this.weChatOrderUuid = resp.data.data.serialNumber
          //console.log(this.weChatOrderUuid)
        })
        // getNativeCodeUrl2({
        //   preparidAmount: this.z_money,
        //   // memberId: this.$store.state.user.id,
        //   orderNo: this.$store.state.carinfo.orderNo,
        //   carId: this.$store.state.carinfo.id,
        //   // startTime: this.$store.state.startime,
        //   // endTime: this.$store.state.endtime,
        //   // brrowShop: this.$store.state.brrowShop,
        //   // returnShop: this.$store.state.brrowShop
        // })
        //     .then((res) => {
        //       console.log(res.data.code_url)
        //       this.code_url = res.data.codeUrl;
        //       //map.put("id", order.getOrderno());
        //       this.id = res.data.id;
        //       this.preparidAmount = res.data.preparidAmount;
        //       this.$store.state.order.orderno = res.data.id;
        //     });
      }
      if (this.radio == "支付宝") {
        this.show3 = true
        this.orderMsg.state = 0
        this.$http.post("/rent/order/productionAliPay", this.orderMsg).then(res => {
          this.code_url = res.data.data
          this.apiPayOrderUuid = res.data.msg
        })
      }

      if (this.radio == "账户余额") {
        this.show1 = true;
      }
      // if (this.z_money > this.$store.state.user.accountBalance) {
      //   console.log("--" + this.z_money),
      //       console.log("--" + this.$store.state.user.accountBalance),
      //       Notify({type: "danger", message: "余额不足请充值"});
      //   this.$router.push("/wallet");
      // } else {
      //   pay({
      //     orderNo: this.$store.state.carinfo.orderNo,
      //     username: this.$store.state.user.username,
      //     totalPrice: this.z_money, //支付金额
      //   }).then((res) => {
      //     this.$store.state.order = res;
      //     this.$router.push("/dingdantongzhi");
      //   });
      // }
    },
  }
  ,
  mounted() {
    let money = this.$store.state.carinfo.price;
    let stime = this.$store.state.startime_;
    let etime = this.$store.state.endtime_;
    //alert("money"+money+"stime"+stime+"etime"+etime)
    let time = (etime - stime) / 24 / 60 / 60 / 1000;
    this.z_money = (money - 0) * time;
    this.price = this.z_money
    // console.log(this.$store.state.carinfo.id)
    // onExchange = (code) => {
    //   coupons.value.push(coupon);
    // };
  }
  ,
  components: {}
  ,
}
;
</script>

<style scoped lang="less">
.dingjin {
  width: 100%;
  margin-top: 0.05rem;
  font-size: 15px;

  .yingfu {
    width: 95%;
    height: 0.73rem;
    margin: 0 auto;
    border-radius: 0.08rem;
    background: white;
    line-height: 0.73rem;
    padding-left: 0.15rem;

    span {
      font-size: 0.25rem;
      font-weight: 600;
    }

    span:last-child {
      color: #f0230e;
    }
  }

  .fuzhang {
    width: 95%;
    height: 3.2rem;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    margin: 0 auto;
    margin-top: 0.25rem;
    position: relative;

    li {
      flex: 1;
      display: flex;
      align-items: center;

      img {
        width: 0.6rem;
        height: 0.6rem;
        border-radius: 0.08rem;
      }

      span {
        font-size: 0.26rem;
        margin-left: 0.26rem;
        font-weight: 600;
      }
    }
  }

  .tongyi_yuedu {
    width: 95%;
    margin: 0.27rem auto 0.6rem auto;
    display: flex;
    align-items: center;

    span:nth-child(2) {
      font-size: 0.22rem;
      color: #666;
      margin-left: 0.2rem;
    }

    span:last-child {
      font-size: 0.23rem;
      color: #4395ff;
      margin-left: 0.29rem;
    }
  }

  .buton_botom {
    width: 100%;
    height: 0.81rem;
    background: #4395ff;
    color: white;
    font-size: 0.29rem;
  }

  .sg-qrcode {
    /*color: deepskyblue;*/
    color: #2ba245;
  }
}
</style>
